#include "recvfile.h"
#include <QDebug>
#include <QFileInfo>
#include <QFileDialog>
#include <QHostAddress>

RecvFile::RecvFile(QTcpSocket *cfd, QObject *parent) : QThread(parent)
{
    this->cfd = cfd; 
}

RecvFile::~RecvFile()
{
    this->file->deleteLater(); 
}

void RecvFile::run()
{
    connect(cfd, &QTcpSocket::readyRead, this, [=]()
    {
        qDebug() << "readyread"; 
        if(!this->file_size) 
        {
            qDebug() << "test1"; 
            qDebug() << this->cfd->bytesAvailable(); 
            this->cfd->read((char*)&this->file_size, sizeof(int)); 
            qDebug() << this->cfd->bytesAvailable(); 
        }
        
        if(!this->file) 
        {
            qDebug() << "test2"; 
            qDebug() << this->cfd->bytesAvailable(); 
            QByteArray filename = this->cfd->readLine().simplified(); 
            qDebug() << filename; 
            this->file = new QFile(filename); 
            if(!this->file->open(QFile::WriteOnly)) 
            {
                emit openfile_error(); 
                return;
            }
            qDebug() << this->cfd->bytesAvailable(); 
        }
        QByteArray all = this->cfd->readAll(); 
        this->recv_size += all.size();               
        qDebug() << this->recv_size; 
        file->write(all); 

        // 文件接收完成
        if(this->recv_size == this->file_size) 
        {
            this->file_size = 0; 
            this->recv_size = 0; 
            //this->cfd->close(); 
            //this->cfd->deleteLater(); 
            file->close(); 
            file->deleteLater(); 
            file = nullptr; 
            emit recv_ok(); 
        }
    }); 

    // 收到客户端断开连接请求 
    connect(cfd, &QTcpSocket::disconnected, this, &RecvFile::disconnect);

    // 进入事件循环防止子线程退出 
    this->exec(); 
}

